'usescript';

$(document).ready(function () {

    var config;
    //先去读取配置然后执行
    chrome.storage.local.get('config', function (item) {
        //拿到配置后再去执行
        config = item.config;
    });

    //定义一个按钮
    var button = '<a href="javascript:void(0)" id="dfs_query_deliver" class="dfs_staus dfs_button"> dfs168查询物流 </a>';
    //加入到页面里
    $("#step3>h3:first").append(button);

    //点击查询按钮
    $("#dfs_query_deliver").click(function () {

        var order_sn = $('#J_TaobaoTradeId').val();

        //如果没有配置是不能使用的
        if (!config || !config.query_deliver_api) {
            layer.open({title: '错误提示', content: '缺少接口地址的配置！', time: 2500});
            return false;
        }

        if (!order_sn) {
            layer.open({title: '错误提示', content: '缺少参数，无法进行查询！', time: 2500});
            return false;
        }

        var requestObject = {
            'url': config.query_deliver_api,
            'method': 'get',
            'dataType': 'json',
            'data': {'order_sn': order_sn}
        };


        chrome.runtime.sendMessage(requestObject, function (response) {

            console.log(response);

            if (!response || !response.code) {
                layer.open({title: '错误', content: '没有收到响应！', time: 2500});
                return false;
            }

            if (response.code != 200) {
                layer.open({title: response.code + '错误', content: response.msg, time: 2500});
                return false;
            }

            var json = response.data;

            if (json.state != 1) {
                layer.open({title: '错误', content: json.msg, time: 2500});
                return false;
            }
            //渲染物流页面
            showLogis(json.data);
        });
    });
});

//显示物流表
function showLogis(data) {
    console.log(data);

    if(data.length < 1)
    {
        layer.open({title: '提示', content: '暂时没有查询到相关物流信息'});return false;
    }
   var html =  '<table class="pure-table pure-table-bordered" style="margin: 20px;">'+
    '    <thead>'+
    '        <tr><th>#</th><th>物流单号</th><th>物料编码</th><th>物料</th><th>规格</th><th>数量</th><th>时间</th></tr>'+
    '    </thead>'+
    '    <tbody>';

    for(var i in data)
    {
        var j = parseInt(i) + 1;
        html += '<tr>';
        html += '<th>'+ j +'</th>';
        html += '<td>'+ data[i].shipping_code +'</td>';
        html += '<td>'+ data[i].stocks_sn +'</td>';
        html += '<td>'+ data[i].stocks_name +'</td>';
        html += '<td>'+ data[i].stocks_spec +'</td>';
        html += '<td>'+ data[i].quantity +'</td>';
        html += '<td>'+ data[i].shipping_time +'</td>';
        html += '</tr>';
    }
    html += '</tbody></table>';

    layer.open({
        type: 1,
        title: '订单发货信息',
        offset: 'lb',
        shade:0,
        closeBtn: 1,
        skin: 'layui-layer-rim', //加上边框
        area: ['800px', '350px'], //宽高
        content: html
    });
}
